const urlInput = document.getElementById('url');
const goButton = document.getElementById('go');
const backButton = document.getElementById('back');
const forwardButton = document.getElementById('forward');
const reloadButton = document.getElementById('reload');
const searchContainer = document.getElementById('search-container');
const hoverArea = document.getElementById('hover-area');

// 设置默认搜索引擎
const DEFAULT_SEARCH_ENGINE = 'https://www.baidu.com/s?wd=';

// 等待 webview 元素完全加载
let webview;
function initWebview() {
    webview = document.getElementById('webview');

    // 确保 webview 已加载
    if (!webview || !webview.getURL) {
        setTimeout(initWebview, 100);
        return;
    }

    // 绑定 webview 事件
    webview.addEventListener('dom-ready', () => {
        // 安全更新 UI
        updateUI();
    });

    // 其他事件监听
    webview.addEventListener('did-finish-load', updateUI);
    webview.addEventListener('did-navigate-in-page', updateUI);
    webview.addEventListener('did-navigate', updateUI);

    // 处理新窗口请求
    webview.addEventListener('new-window', (e) => {
        e.preventDefault();
        navigate(e.url);
    });

    // 初始更新
    updateUI();
}

// 优化导航功能
function navigate(input) {
    const trimmedInput = input.trim();
    if (!trimmedInput) return;

    try {
        if (!trimmedInput.includes('://')) {
            if (/^[a-zA-Z0-9-]+\.[a-zA-Z]{2,}/.test(trimmedInput)) {
                webview.src = `https://${trimmedInput}`;
                return;
            }
            const searchUrl = DEFAULT_SEARCH_ENGINE + encodeURIComponent(trimmedInput);
            webview.src = searchUrl;
            return;
        }

        const url = new URL(trimmedInput);
        webview.src = url.href;
    } catch (e) {
        const searchUrl = DEFAULT_SEARCH_ENGINE + encodeURIComponent(trimmedInput);
        webview.src = searchUrl;
    }
}

// 按钮事件监听
goButton.addEventListener('click', () => {
    if (webview) navigate(urlInput.value);
});

urlInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        if (webview) navigate(urlInput.value);
        urlInput.blur();
    }
});

backButton.addEventListener('click', () => {
    if (webview && webview.canGoBack) webview.goBack();
});

forwardButton.addEventListener('click', () => {
    if (webview && webview.canGoForward) webview.goForward();
});

reloadButton.addEventListener('click', () => {
    if (webview) webview.reload();
});

// 安全更新 UI
function updateUI() {
    if (!webview || typeof webview.getURL !== 'function') return;

    try {
        const currentUrl = webview.getURL();
        urlInput.value = currentUrl.replace(/^https?:\/\//, '');

        if (webview.canGoBack) {
            backButton.disabled = !webview.canGoBack();
        }

        if (webview.canGoForward) {
            forwardButton.disabled = !webview.canGoForward();
        }
    } catch (e) {
        console.error('更新 UI 出错:', e);
    }
}

// 顶部区域交互
hoverArea.addEventListener('mouseenter', () => {
    searchContainer.style.display = 'block';
});

searchContainer.addEventListener('mouseleave', (e) => {
    if (!searchContainer.contains(e.relatedTarget)) {
        searchContainer.style.display = 'none';
    }
});

urlInput.addEventListener('focus', () => {
    searchContainer.style.display = 'block';
});

urlInput.addEventListener('blur', () => {
    setTimeout(() => {
        if (!searchContainer.matches(':hover')) {
            searchContainer.style.display = 'none';
        }
    }, 100);
});

// 初始化 webview
initWebview();